package com.na.flipcard.ui;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.Rect;
import android.view.MotionEvent;
import cn.bmob.BmobObject;

import com.na.flipcard.Game;
import com.na.flipcard.NamedActivity;
import com.na.flipcard.props.DoubleScore;
import com.na.flipcard.util.GameConfigEx;
import com.na.flipcard.util.GameUtil;
import com.na.game.GameActivity;
import com.na.game.GameManager;
import com.na.game.data.DataManager;
import com.na.game.event.impl.EventAdapter;
import com.na.game.event.impl.KeyEvent;
import com.na.game.event.impl.TouchEvent;
import com.na.game.graphics.Graphics;
import com.na.game.graphics.Image;
import com.na.game.graphics.Painter;
import com.na.game.platform.sns.SnsListener;
import com.na.game.platform.sns.SnsManager;
import com.na.game.props.GameProps;
import com.na.game.props.PropsManager;
import com.na.game.resource.ResourceManager;
import com.na.game.sound.SoundManager;
import com.na.game.ui.UI;
import com.na.game.ui.UIManager;
import com.na.game.util.Cache;
import com.na.game.util.GameConfig;
import com.na.game.util.GameException;
import com.na.game.util.Util;
import com.na.game.widget.impl.Button;
import com.na.game.widget.impl.Container;
import com.na.game.widget.impl.Label;
import com.na.game.widget.impl.TextArea;

public class GameOverUI extends UI {

	private Game game;
	private DataManager dm;
	
	public GameOverUI(Game game) {
		this.game = game;
		dm = GameManager.get(DataManager.class);
	}
	
	@Override
	public void init() {
		
		Container ui = new Container();
		ui.setBound(0, 0, GameConfig.STANDARD_WIDTH, GameConfig.STANDARD_HEIGHT);
		setWidget(ui);
		setTransparent(true);
		
		ResourceManager rm = GameManager.get(ResourceManager.class);
		
		Image image = rm.getImageFromAssets(GameConfigEx.RES_GAME_PANEL);
		int w = 680;
		int h = 130;
		int x = (GameConfig.STANDARD_WIDTH - w) >> 1;
		int y = (GameConfig.STANDARD_HEIGHT - 700/*total h*/) >> 1;
		Button title = new Button(image, "游戏结束", Color.WHITE);
		ui.addChild(title);
		title.setBound(x, y, w, h);
		title.setScaled(true);
		title.setSrcRect(new Rect(0, 0, image.getWidth(), image.getHeight()));
		title.setImageColor(0xffa68039);
		
		y += h;
		h = 440;
		final Container panel = new Container(3);
		ui.addChild(panel);
		panel.setBound(x, y, w, h);
		panel.setPainter(new Painter() {
			private Image image = GameManager.get(ResourceManager.class).getImageFromAssets(GameConfigEx.RES_GAME_PANEL);
			@Override
			public void paint(Graphics g) {
				Rect rect = panel.getAbsBound();
				Rect dst = new Rect(rect.left, rect.top - 100, rect.right, rect.bottom + 100);
				g.setColorFilter(0xffc8d7b3);
				g.drawImage(image, new Rect(0, 0, image.getWidth(), image.getHeight()), dst);
				g.setColorFilter(Graphics.COLOR_FILTER_NULL);
			}
		});
		
		w = Util.getTextWidth("得分:x", 30);
		int totalW = w + Util.getTextWidth(String.valueOf(game.getScore())) + 20;
		h = Util.getTextHeight("得");
		x = (panel.getBound().width() - totalW) / 2;
		y = 20;
		Label score1 = new Label("得分: ", false, Color.WHITE, 0, 30);
		panel.addChild(score1);
		score1.setBound(x, y, w, h);
		
		x += w;
		w = totalW - w;
		Label score2 = new Label(String.valueOf(game.getScore()), true, 0xFFFF0000, 0xFFFFFFFF);
		panel.addChild(score2);
		score2.setBound(x, y, w, h);
		
		y += h;
		w = panel.getBound().width() - 80;
		h = panel.getBound().height() - y;
		x = 50;
		TextArea detail = new TextArea(getDetailText());
		panel.addChild(detail);
		detail.setBound(x, y, w, h);
//		detail.setPainter(new Util.DebugPainter(detail));
		
		Image[] images = new Image[]{
				GameManager.get(ResourceManager.class).getImageFromAssets(GameConfigEx.RES_LONG_BUTTON),
				GameManager.get(ResourceManager.class).getImageFromAssets(GameConfigEx.RES_LONG_BUTTON_PRESSED)
		};
		w = panel.getBound().width() / 2;
		h = 130;
		x = panel.getBound().left;
		y = panel.getBound().bottom;
		Button goBack = new Button(images, "返回", 0xFF000000);
		ui.addChild(goBack);
		goBack.setBound(x, y, w, h);
		goBack.setScaled(true);
		goBack.setSrcRect(new Rect(0, 0, images[0].getWidth(), images[0].getHeight()));
		goBack.setImageColor(0xffa68039);
		goBack.setEventListener(new EventAdapter() {
			@Override
			public boolean onTouch(TouchEvent event) {
				switch (event.action) {
					case MotionEvent.ACTION_UP:
						GameManager.get(UIManager.class).popUI();
						GameManager.get(UIManager.class).popUI();
						break;
					case MotionEvent.ACTION_DOWN:
						GameManager.get(SoundManager.class).play(GameConfigEx.RES_SOUND_CLICK);
						break;
				}
				return true;
			}
		});
		
		x += w;
		Button again = new Button(images, "再来一局", 0xFF000000);
		ui.addChild(again);
		again.setBound(x, y, w, h);
		again.setScaled(true);
		again.setSrcRect(new Rect(0, 0, images[0].getWidth(), images[0].getHeight()));
		again.setImageColor(0xffa68039);
		again.setEventListener(new EventAdapter() {
			@Override
			public boolean onTouch(TouchEvent event) {
				switch (event.action) {
					case MotionEvent.ACTION_UP:
						GameManager.get(UIManager.class).popUI();
						GameManager.get(UIManager.class).popUI();
						GameManager.get(UIManager.class).pushUI(new StartGameUI());
						break;
					case MotionEvent.ACTION_DOWN:
						GameManager.get(SoundManager.class).play(GameConfigEx.RES_SOUND_CLICK);
						break;
				}
				return true;
			}
		});
		
		submitScore();
		GameManager.get(PropsManager.class).clear();
	}

	@Override
	public boolean onKey(KeyEvent event) {
		if (event.action == android.view.KeyEvent.ACTION_UP && event.keyCode == android.view.KeyEvent.KEYCODE_BACK) {
			GameManager.get(UIManager.class).popUI();
			GameManager.get(UIManager.class).popUI();
		}
		return true;
	}
	
	private String getDetailText() {
		Object data = dm.get(GameConfigEx.DATA_SAVE_SCORE_DATE);
		if (data == null) {
			dm.put(GameConfigEx.DATA_SAVE_SCORE_DATE, String.valueOf(System.currentTimeMillis()));
			dm.put(GameConfigEx.DATA_SCORE_HIGHEST_DAY, game.getScore());
			dm.put(GameConfigEx.DATA_SCORE_HIGHEST_WEEK, game.getScore());
			dm.put(GameConfigEx.DATA_SCORE_HIGHEST_ALL, game.getScore());
			return GameConfigEx.GAME_OVER_DESC_FIRST_WIN;
		}
		String desc = GameConfigEx.GAME_OVER_DESC_NORMAL;
		Calendar old = Calendar.getInstance();
		old.setTimeInMillis(Long.parseLong(data.toString()));
		int oldDay = old.get(Calendar.DAY_OF_YEAR);
		int oldWeek = old.get(Calendar.WEEK_OF_YEAR);
		
		Calendar c = Calendar.getInstance();
		int day = c.get(Calendar.DAY_OF_YEAR);
		int week = c.get(Calendar.WEEK_OF_YEAR);
		
		data = dm.get(GameConfigEx.DATA_SCORE_HIGHEST_DAY);
		if (data == null || oldDay != day || (Integer) data < game.getScore()) {
			dm.put(GameConfigEx.DATA_SAVE_SCORE_DATE, String.valueOf(System.currentTimeMillis()));
			dm.put(GameConfigEx.DATA_SCORE_HIGHEST_DAY, game.getScore());
			desc = GameConfigEx.GAME_OVER_DESC_HIGHEST_DAY;
		}
		data = dm.get(GameConfigEx.DATA_SCORE_HIGHEST_WEEK);
		if (data == null || oldWeek != week || (Integer) data < game.getScore()) {
			dm.put(GameConfigEx.DATA_SAVE_SCORE_DATE, String.valueOf(System.currentTimeMillis()));
			dm.put(GameConfigEx.DATA_SCORE_HIGHEST_WEEK, game.getScore());
			desc = GameConfigEx.GAME_OVER_DESC_HIGHEST_WEEK;
		}
		data = dm.get(GameConfigEx.DATA_SCORE_HIGHEST_ALL);
		if (data == null || (Integer) data < game.getScore()) {
			dm.put(GameConfigEx.DATA_SAVE_SCORE_DATE, String.valueOf(System.currentTimeMillis()));
			dm.put(GameConfigEx.DATA_SCORE_HIGHEST_ALL, game.getScore());
			desc = GameConfigEx.GAME_OVER_DESC_HIGHEST_ALL;
		}
		GameProps[] gps = GameManager.get(PropsManager.class).getProps();
		for (GameProps gp : gps) {
			if (gp instanceof DoubleScore) {
				return desc + "\n使用了\"双倍积分\",果然更厉害啊";
			}
		}
		return desc;
	}

	private void submitScore() {
		if (game.getScore() <= 0) {
			return;
		}
		SnsManager sns = GameManager.get(SnsManager.class);
		SnsListener listener = new SnsListener() {
			@Override
			public void saveCallback(String msg) {
				GameManager.get(DataManager.class).put(GameConfigEx.DATA_SUBMIT_SCORE, Integer.valueOf(127)); // mark
				Util.showToast(msg == null ? "分数提交成功,您可以到排行榜去查看您的战绩" : msg);
			}
			
			@Override
			public void queryResult(List<BmobObject> result, GameException ex) {
				submitScore(); // retry one time
			}
		};
		
		BmobObject bmob = (BmobObject) Cache.getCache().get(GameConfigEx.CACHE_BMOB_SCORE);
		if (bmob == null) {
			GameUtil.cacheBmob(listener);
			return;
		}
		ArrayList<Object> values = new ArrayList<Object>();
		String deviceId = bmob.getString(GameConfigEx.BMOB_TABLE_SCORES_COL_USERID);
		if (deviceId == null) { // may be error or first time, try fix
			values.add(GameConfigEx.BMOB_TABLE_SCORES_COL_USERID);
			values.add(Util.getDeviceId());
		}
		int highest = bmob.getInt(GameConfigEx.BMOB_TABLE_SCORES_COL_HIGHEST);
		if (highest < dm.get(GameConfigEx.DATA_SCORE_HIGHEST_ALL, 0)) {
			highest = dm.get(GameConfigEx.DATA_SCORE_HIGHEST_ALL, 0);
			values.add(GameConfigEx.BMOB_TABLE_SCORES_COL_HIGHEST);
			values.add(highest);
		}
		values.add(GameConfigEx.BMOB_TABLE_SCORES_COL_ADDITIVE);
		values.add(game.getScore() + bmob.getInt(GameConfigEx.BMOB_TABLE_SCORES_COL_ADDITIVE));
		
		if (bmob.getString(GameConfigEx.BMOB_TABLE_SCORES_COL_USERID) == null) {
			GameActivity context = GameManager.get(GameActivity.class);
			Intent intent = new Intent(context, NamedActivity.class);
			intent.putExtra(NamedActivity.EXTRA_DATA, values);
			context.startActivity(intent);
			return;
		}
		
		String table = GameConfigEx.BMOB_TABLE_SCORES;
		
		sns.save(bmob, table, values.toArray(), listener);
	}
	
}
